//
//  EditImageController.m
//  ImageFilter
//
//  Created by 冀秋羽 on 15/7/22.
//  Copyright (c) 2015年 冀秋羽. All rights reserved.
//

#import "EditImageController.h"
#import "ImageUtil.h"
#import "ColorMatrix.h"
#import "ReleaseMainVC.h"
#import "ImageFilterColCell.h"
#import "YSHYClipViewController.h"
#import "SendSynchronousVC.h"

//加上图层效果ctrl
@interface EditImageController ()<UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
ClipViewControllerDelegate,SendSynchronousVCDelegate>
@property (weak, nonatomic) IBOutlet UIButton *tbbtn;
@property (nonatomic,strong) NSArray *filterNames;
@property (weak, nonatomic) IBOutlet UIView *imgview;
@property (nonatomic,copy) NSMutableArray *filterImages;

@property(nonatomic, strong) NSArray *filterColorMatrixs;

@end

@implementation EditImageController

static NSString * const  filterColCellID = @"filterColCellID";
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _filterColorMatrixs = @[@"",
                            @"heibai",
                            @"huaijiu",
                            @"gete",
                            @"danya",
                            @"jiuhong",
                            @"qingning",
                            @"langman",
                            @"guangyun",
                            @"landiao",
                            @"menghuan",
                            @"yese"];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.icon.contentMode = UIViewContentModeScaleAspectFit;
    
    [self initCollectionView];
}
-(void)viewWillAppear:(BOOL)animated{
    self.icon.image = _image;
    CGRect r = _tbbtn.frame;
    r.size.width = SCRE_WIDTH;
    _tbbtn.frame = r;
    
    self.filterImages = nil;
    
    [self.collectionView reloadData];
}

- (NSMutableArray *)filterImages {
    if (!_filterImages) {
        _filterImages = [[NSMutableArray alloc] init];
        [_filterColorMatrixs enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [_filterImages addObject:[[NSNull alloc] init]];
        }];
    }
    return _filterImages;
}


- (void)initCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //    flowLayout.minimumInteritemSpacing = 0;
    //    flowLayout.minimumLineSpacing = 0;
    
    //    CGFloat colMargin = 5;
    //    flowLayout.itemSize = CGSizeMake(90, 90);
    //    flowLayout.sectionInset = UIEdgeInsetsMake(0,colMargin, colMargin, colMargin);  //上左下右
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    //    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.collectionViewLayout = flowLayout;
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerNib:[ImageFilterColCell nib] forCellWithReuseIdentifier:filterColCellID];
    
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.f;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,1, 1, 1);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake(90,120);
    return size;
}
- (void)saveImageToAlbum {
    UIImageWriteToSavedPhotosAlbum(self.icon.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

//实现imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:方法

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = @"";
    if (!error) {
        message = @"成功保存到相册";
    }else
    {
        message = [error description];
    }
    NSLog(@"message is %@",message);
    
    //弹窗提示
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"cencel----");
    }];
    
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.filterNames.count;
}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    CGSize size = CGSizeMake((SCRE_WIDTH)/4-0.5, (SCRE_WIDTH-10)/4-5);
//
//    return size;
//}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageFilterColCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:filterColCellID forIndexPath:indexPath];
    cell.filterNameLabel.text = self.filterNames[indexPath.item];
    
    
    cell.imageView.image = nil;
    
    
    
    if (![self.filterImages[indexPath.item] isKindOfClass:[NSNull class]]) {
        cell.imageView.image = self.filterImages[indexPath.item];
    } else {
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            const float *colorMatrixs;
            if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"heibai"]) {
                colorMatrixs = colormatrix_heibai;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"huaijiu"]) {
                colorMatrixs = colormatrix_huaijiu;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"gete"]) {
                colorMatrixs = colormatrix_gete;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"danya"]) {
                colorMatrixs = colormatrix_danya;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"jiuhong"]) {
                colorMatrixs = colormatrix_jiuhong;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"qingning"]) {
                colorMatrixs = colormatrix_qingning;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"langman"]) {
                colorMatrixs = colormatrix_langman;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"guangyun"]) {
                colorMatrixs = colormatrix_guangyun;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"landiao"]) {
                colorMatrixs = colormatrix_landiao;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"menghuan"]) {
                colorMatrixs = colormatrix_menghuan;
            } else if ([self.filterColorMatrixs[indexPath.item] isEqualToString:@"yese"]) {
                colorMatrixs = colormatrix_yese;
            } else {
                colorMatrixs = nil;
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (colorMatrixs) {
                    cell.imageView.image = [ImageUtil imageWithImage:self.image withColorMatrix:colorMatrixs];
                } else {
                    //原图
                    cell.imageView.image = self.image;
                }
                
                self.filterImages[indexPath.item] = cell.imageView.image;
            });
            
        });
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (![self.filterImages[indexPath.item] isKindOfClass:[NSNull class]]) {
        self.icon.image = self.filterImages[indexPath.item];
    }
}
- (IBAction)nexitAction:(UIButton *)sender {
    if (self.commitImage) {
        self.commitImage(self.icon.image);
    } else {
        //xhw2018-1-16加
        if (self.InType == 1) {  //拍照只有动态需要选择裁剪封面图片，其他模式中的拍照都不需要
            YSHYClipViewController * clipView = [[YSHYClipViewController alloc]initWithImage:self.icon.image];
            clipView.delegate = self;
            //xhw11月24号加
            clipView.InType = self.InType;
            
            
            clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
            clipView.radius = SCRE_WIDTH/2.0;   //设置 裁剪框的半径  默认120
            clipView.presentVC = self;
            [self presentViewController:clipView animated:YES completion:nil];
        }
        else { //直接跳转到是否发布到附近界面
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"KP" bundle:nil];
            SendSynchronousVC *sendSynVC = [sb instantiateViewControllerWithIdentifier:@"SendSynchronousVC"];
            //跳转代码
            sendSynVC.delegate = self;
            sendSynVC.tpImge = self.icon.image;
            [self presentViewController:sendSynVC animated:YES completion:nil];
        }
        //选择封面
        
//        YSHYClipViewController * clipView = [[YSHYClipViewController alloc]initWithImage:self.icon.image];
//        clipView.delegate = self;
//        //xhw11月24号加
//        clipView.InType = self.InType;
//
//
//        clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
//        clipView.radius = SCRE_WIDTH/2.0;   //设置 裁剪框的半径  默认120
//        clipView.presentVC = self;
//        [self presentViewController:clipView animated:YES completion:nil];
    }
}

-(NSArray *)filterNames
{
    if (!_filterNames) {
        _filterNames = [NSArray arrayWithObjects:@"原始",@"黑白",@"怀旧",@"哥特",@"淡雅",@"酒红",@"清宁",@"浪漫",@"光晕",@"蓝调",@"梦幻",@"夜色", nil];
    }
    return _filterNames;
}
////原始,lomo,黑白,怀旧,哥特,淡雅,酒红,清宁,浪漫,光晕,蓝调,梦幻,夜色
//-(NSArray *)filterImages
//{
//    [SVProgressHUD showWithStatus:@"加载中..."];
//      [SVProgressHUD dismiss];
//    return _filterImages;
//
//}
- (IBAction)backAction:(UIButton *)sender {
    
    NSInteger count = _backVCCount;
    UIViewController *VC = self;
    while (count) {
        VC = VC.presentingViewController;
        count--;
    }
    [VC dismissViewControllerAnimated:NO completion:nil];
    
    [SVProgressHUD dismiss];
}

#pragma mark - ClipViewControllerDelegate
//-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage
//{
//    [self sendDataToServerWithEditImage:editImage];
//}

//将截取封面图之后的界面中的title、是否发布到附近的人等参数也传上去(xhw9月20日改)
- (void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage param:(NSDictionary *)dic {
    [self sendDataToServerWithEditImage:editImage param:dic];
}

- (void)sendDataToServerWithEditImage:(UIImage *)editImage param:(NSDictionary *)paramter {
    
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uid"];
    
    NSString *title = [paramter objectForKey:@"title"];
    if (title) {
       [dic setObject:title forKey:@"title"];
    }
    NSNumber *isSendNearBy = [paramter objectForKey:@"isSendNearBy"];
    
    [dic setObject:isSendNearBy forKey:@"tonearyby"];
    
    NSNumber *isSynchronizeToDynamic = [paramter objectForKey:@"isSynchronizeToDynamic"];

    [dic setObject:isSynchronizeToDynamic forKey:@"todynamic"];

    
    
    
    NSMutableArray *imgdata =[[NSMutableArray alloc]init];
    NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
    [dici setObject:@"file" forKey:@"key"];
    [dici setObject:UIImageJPEGRepresentation(self.image, 0.00001) forKey:@"value"];
    [imgdata addObject:dici];
    NSMutableDictionary *dic2 = [[NSMutableDictionary alloc]init];
    [dic2 setObject:@"img" forKey:@"key"];
    [dic2 setObject:UIImageJPEGRepresentation(editImage, 0.00001) forKey:@"value"];
    [imgdata addObject:dic2];
    
    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:publish_kuaipaiurl postParems:dic data:imgdata];
    [[NSURLConnection connectionWithRequest:request delegate:self] start];
    
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
    float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
    float progres = progress/total;
    [SVProgressHUD showProgress:progres status:@"发布中..."];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)datas{
    NSString *request= [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result = [ValidateHelper jsonStringToDictionary:request];
    int code = [[[result objectForKey:@"state"] objectForKey:@"code"] intValue];
    if(code == 0){
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        //把最前面的视图控制器dismiss掉
        UIViewController *parentVC = self.presentingViewController;
        UIViewController *bottomVC;
        while (parentVC) {
            bottomVC = parentVC;
            parentVC = parentVC.presentingViewController;
        }
        
        //创建通知
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNotification *notification = [NSNotification notificationWithName:@"public" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            
            //xhw12月28号加:同步到动态之后，在我的资料详细里面的动态也应该刷新
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDynamicDataOfMyInformation" object:nil];
        });
        
        [bottomVC dismissViewControllerAnimated:YES completion:nil];
    }else{
        [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
    }
}

#pragma mark SendSynchronousVCDelegate
- (void)SendSynchronousVC:(SendSynchronousVC *)SendSynchronousVC  param:(NSDictionary *)dic {
    YSHYClipViewController * ctrl = [[YSHYClipViewController alloc] init];
    [self ClipViewController:ctrl FinishClipImage:self.icon.image param:dic];
}

@end
